package com.example.shiro.shiro;

import com.example.shiro.po.Permission;
import com.example.shiro.po.Role;
import com.example.shiro.po.User;
import com.example.shiro.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @author xyh
 * @description
 * @date 2021/4/1 16:28
 */

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;


    /**
     *
     * 1，登陆，根据在登陆接口里封装的UsernamePasswordToken ，取得userName，与从数据库中查出对应的的账号密码，返回上层作对比，以达到登陆的效果
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = null;
        User user = null;
        if(authenticationToken instanceof UsernamePasswordToken){
            usernamePasswordToken = (UsernamePasswordToken)authenticationToken;
            user = loginService.getUserByUserName(usernamePasswordToken.getUsername());

        }

        user.setToken(UUID.randomUUID().toString());
        return new SimpleAuthenticationInfo(user, usernamePasswordToken.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
    }


    /**
     * 2，登陆成功后授权用户角色与权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Object userObj =  principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = null;
        if(userObj != null){
            User user = (User)userObj;
            simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            for(Role role:user.getRoles()){
                for(Permission p:role.getPermission()){
                    simpleAuthorizationInfo.addStringPermission(p.getName());
                }
            }
        }
        return simpleAuthorizationInfo;
    }

}
